package com.example.nonggo.convert;

 

import android.util.Log;

import com.example.nonggo.bean.MBaseData;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ResultJsonDeser implements JsonDeserializer<MBaseData<?>> {
    private final String  TAG ="ResultJsonDeser" ;

    @Override
    public synchronized MBaseData<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        MBaseData<?> response = new MBaseData<>();
        try {
            if (json.isJsonObject()) {
                JsonObject jsonObject = json.getAsJsonObject();
//                Log.e(TAG,"<<< HTTP response data:" + jsonObject);
                JsonElement dataElement = jsonObject.get("data");
                response.setResult(jsonObject.get("code").getAsInt());
                response.setMessage(jsonObject.get("msg").getAsString());
                    if (!(jsonObject instanceof JsonObject)) {
                        Log.e(TAG, "jsonObject is not a JsonObject");
                    }

                if (!hasData(dataElement)) {
                    return response;
                }
                if (!jsonObject.get("data").isJsonNull()){
                    Type itemType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0];
                    response.setData(context.deserialize(jsonObject.get("data"), itemType));
                }
                return response;
            }
        } catch (JsonParseException e) {
            e.printStackTrace();
            Log.e(TAG,"Gson convert error"+e.getMessage());
            throw e;
        }

        return response;
    }

    /**
     * Judge whether has the data
     *
     * @param dataElement
     * @return
     */
    private boolean hasData(JsonElement dataElement) {
        return !dataElement.toString().equals("\"\"") || dataElement.isJsonObject();
    }
}
